package com.ysd.lis.service.qc.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.entity.PubEmployee;
import com.ysd.lis.entity.SysUser;
import com.ysd.lis.entity.lab.LabInstrSetup;
import com.ysd.lis.entity.lab.LabItemDict;
import com.ysd.lis.entity.lab.LabRptGroup;
import com.ysd.lis.entity.qc.QcMaterialItemResult;
import com.ysd.lis.entity.qc.QcMaterialItemResultQuery;
import com.ysd.lis.entity.qc.QcOutControlRec;
import com.ysd.lis.entity.qc.QcOutControlRecDetail;
import com.ysd.lis.mapper.qc.QcMaterialItemResultMapper;
import com.ysd.lis.mapper.qc.QcOutControlRecDetailMapper;
import com.ysd.lis.mapper.qc.QcOutControlRecMapper;
import com.ysd.lis.request.qc.QcPageDto;
import com.ysd.lis.service.qc.QcOutControlRecDetailService;
import com.ysd.lis.service.qc.QcOutControlRecService;
import com.ysd.util.ToolsUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * cold_chain.t_user 服务实现类
 * </p>
 *
 * @author peng
 * @since 2024-01-20
 */
@Service
@Slf4j
public class QcOutControlRecServiceImpl extends ServiceImpl<QcOutControlRecMapper, QcOutControlRec> implements QcOutControlRecService {

    @Autowired
    QcOutControlRecMapper qcOutControlRecMapper;
    @Autowired
    QcOutControlRecDetailMapper qcOutControlRecDetailMapper;
    @Autowired
    QcMaterialItemResultMapper qcMaterialItemResultMapper;
    @Autowired
    QcOutControlRecDetailService qcOutControlRecDetailService;

    @Override
    public Result getQcOutControlRecByResultId(String qcResultId) {

        MPJLambdaWrapper<QcOutControlRec> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(QcOutControlRec.class)
                .selectAs("ld", LabItemDict::getItemNa, QcOutControlRec::getItemDictName)
                .selectAs("ls", LabInstrSetup::getInstrName, QcOutControlRec::getInstrName)
                .selectAs("rpt", LabRptGroup::getId,QcOutControlRec::getRptGroupId)
                .selectAs("rpt", LabRptGroup::getRptGroup,QcOutControlRec::getRptGroup)
                .selectAs("rpt", LabRptGroup::getRptGroupName,QcOutControlRec::getRptGroupName)
                .selectAs("em", PubEmployee::getName,QcOutControlRec::getReviewerName)
                .selectAs("res", QcMaterialItemResult::getResult,QcOutControlRec::getCorrectResult)
                .leftJoin(LabItemDict.class,"ld",LabItemDict::getId,QcOutControlRec::getItemDictId)
                .leftJoin(LabInstrSetup.class,"ls",LabInstrSetup::getId,QcOutControlRec::getInstrId)
                .leftJoin(LabRptGroup.class,"rpt",LabRptGroup::getRptGroup,LabItemDict::getRptGroup)
                .leftJoin(PubEmployee.class, "em", on -> on.eq(PubEmployee::getId, QcOutControlRec::getReviewerId).eq(PubEmployee::getDelFlag, 0))
                .leftJoin(QcMaterialItemResult.class,"res",p->p.eq(QcMaterialItemResult::getMaterialId,QcOutControlRec::getMaterialId)
                        .eq(QcMaterialItemResult::getMaterialItemId,QcOutControlRec::getMaterialItemId)
                        .eq(QcMaterialItemResult::getQcDate,QcOutControlRec::getQcDate)
                        .eq(QcMaterialItemResult::getIsBestInDay,1)
                        .eq(QcMaterialItemResult::getIsOutControl,0)
                        .eq(QcMaterialItemResult::getDelFlag,0)
                )
                .eq(QcOutControlRec::getQcResultId,qcResultId)
                .eq(QcOutControlRec::getDelFlag,0);
        QcOutControlRec qcOutControlRec = qcOutControlRecMapper.selectOne(queryWrapper);
        if(null != qcOutControlRec){
            LambdaQueryWrapper<QcOutControlRecDetail> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(QcOutControlRecDetail::getRecId,qcOutControlRec.getId())
                    .eq(QcOutControlRecDetail::getDelFlag,0);
            List<QcOutControlRecDetail> qcOutControlRecDetails = qcOutControlRecDetailMapper.selectList(queryWrapper1);
            qcOutControlRec.setDetails(qcOutControlRecDetails);
        }else {
            MPJLambdaWrapper<QcMaterialItemResult> queryWrapper2 = new MPJLambdaWrapper<>();
            queryWrapper2.selectAll(QcMaterialItemResult.class)
                    .selectAs("ld", LabItemDict::getItemNa, QcMaterialItemResult::getItemDictName)
                    .selectAs("ld", LabItemDict::getItemNo, QcMaterialItemResult::getItemDictCode)
                    .selectAs("ls", LabInstrSetup::getInstrName, QcMaterialItemResult::getInstrName)
                    .selectAs("ls", LabInstrSetup::getInstrCode, QcMaterialItemResult::getInstrCode)
                    .selectAs("rpt", LabRptGroup::getId,QcMaterialItemResult::getRptGroupId)
                    .selectAs("rpt", LabRptGroup::getRptGroup,QcMaterialItemResult::getRptGroup)
                    .selectAs("rpt", LabRptGroup::getRptGroupName,QcMaterialItemResult::getRptGroupName)
                    .selectAs("res", QcMaterialItemResult::getResult,QcMaterialItemResult::getCorrectResult)
                    .leftJoin(LabItemDict.class,"ld",p->p.eq(LabItemDict::getId,QcMaterialItemResult::getItemDictId).eq(LabItemDict::getDelFlag,0) )
                    .leftJoin(LabInstrSetup.class,"ls",p->p.eq(LabInstrSetup::getId,QcMaterialItemResult::getInstrId ).eq(LabInstrSetup::getDelFlag,0) )
                    .leftJoin(LabRptGroup.class,"rpt",p->p.eq(LabRptGroup::getRptGroup,LabItemDict::getRptGroup).eq(LabRptGroup::getDelFlag,0) )
                    .leftJoin(QcMaterialItemResultQuery.class,"res", p->p.eq(QcMaterialItemResultQuery::getMaterialId,QcMaterialItemResult::getMaterialId)
                            .eq(QcMaterialItemResultQuery::getMaterialItemId,QcMaterialItemResult::getMaterialItemId)
                            .eq(QcMaterialItemResultQuery::getQcDate,QcMaterialItemResult::getQcDate)
                            .eq(QcMaterialItemResultQuery::getIsBestInDay,1)
                            .eq(QcMaterialItemResultQuery::getIsOutControl,0)
                            .eq(QcMaterialItemResultQuery::getDelFlag,0)
                     )
                    .eq(QcMaterialItemResult::getDelFlag,0)
                    .eq(QcMaterialItemResult::getId,qcResultId);
            QcMaterialItemResult result = qcMaterialItemResultMapper.selectOne(queryWrapper2);
            qcOutControlRec = new QcOutControlRec();
            BeanUtils.copyProperties(result,qcOutControlRec,"id");
            qcOutControlRec.setOperateDate(new Timestamp(new Date().getTime()));
            qcOutControlRec.setQcResultId(result.getId());
        }

        return Result.succ(1, "查询成功", qcOutControlRec);
    }

    @Override
    public Result saveQcOutControlRec(QcOutControlRec outControlRec) {
        if(ToolsUtils.isEmpty(outControlRec.getId())){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); // 定义日期格式
            String code = sdf.format(outControlRec.getQcDate())
                    + "-"+outControlRec.getInstrCode()
                    + "-"+outControlRec.getItemDictCode()
                    + "-" +outControlRec.getQcNo()
                    + "-"+outControlRec.getQcSequence();
            outControlRec.setCode(code);
        }
        boolean b = this.saveOrUpdate(outControlRec);

        if (b) {

            //根据记录ID找详细信息
            LambdaQueryWrapper<QcOutControlRecDetail> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(QcOutControlRecDetail::getRecId,outControlRec.getId())
                    .eq(QcOutControlRecDetail::getDelFlag,0);
            List<QcOutControlRecDetail> existsDetails = qcOutControlRecDetailMapper.selectList(queryWrapper);


            List<String> inputCodes = outControlRec.getDetails().stream().map(QcOutControlRecDetail::getCode).collect(Collectors.toList());

            List<String> delDetailIds = existsDetails.stream().filter(de -> !inputCodes.contains(de.getCode())).map(QcOutControlRecDetail::getId).collect(Collectors.toList());
            List<QcOutControlRecDetail> existsDetails2 = existsDetails.stream().filter(de -> inputCodes.contains(de.getCode())).collect(Collectors.toList());

            for(QcOutControlRecDetail detail : existsDetails2){
                detail.setResult(outControlRec.getDetails().stream().filter(de->de.getCode().equals(detail.getCode())).findFirst().get().getResult());
            }
            List<String> existsCodes = existsDetails2.stream().map(QcOutControlRecDetail::getCode).collect(Collectors.toList());

            List<QcOutControlRecDetail> insertDetails = outControlRec.getDetails().stream().filter(p -> !existsCodes.contains(p.getCode())).collect(Collectors.toList());

            for(QcOutControlRecDetail detail : insertDetails){
                if(ToolsUtils.isEmpty(detail.getId())){
                    detail.setRecId(outControlRec.getId());
                }
            }
            qcOutControlRecDetailService.removeByIds(delDetailIds);
            qcOutControlRecDetailService.updateBatchById(existsDetails);
            qcOutControlRecDetailService.saveBatch(insertDetails);
            return Result.succ(1, "成功", outControlRec);
        } else {
            return Result.fail(400, "失败", "");
        }
    }

    @Override
    public Result getOutControlRecList(QcPageDto pageParam) {
        MPJLambdaWrapper<QcOutControlRec> queryWrapper = new MPJLambdaWrapper<>();

        queryWrapper.selectAll(QcOutControlRec.class)
                .selectAs("ld", LabItemDict::getItemNa, QcOutControlRec::getItemDictName)
                .selectAs("ls", LabInstrSetup::getInstrName, QcOutControlRec::getInstrName)
                .selectAs("rpt", LabRptGroup::getId,QcOutControlRec::getRptGroupId)
                .selectAs("rpt", LabRptGroup::getRptGroupName,QcOutControlRec::getRptGroupName)
                .selectAs("em", PubEmployee::getName,QcOutControlRec::getReviewerName)
                .leftJoin(LabItemDict.class,"ld",LabItemDict::getId,QcOutControlRec::getItemDictId)
                .leftJoin(LabInstrSetup.class,"ls",LabInstrSetup::getId,QcOutControlRec::getInstrId)
                .leftJoin(LabRptGroup.class,"rpt",LabRptGroup::getRptGroup,LabItemDict::getRptGroup)
                .leftJoin(PubEmployee.class, "em", on -> on.eq(PubEmployee::getId, QcOutControlRec::getReviewerId).eq(PubEmployee::getDelFlag, 0))
                .eq(QcOutControlRec::getDelFlag,0);

        if (StringUtils.isNotBlank(pageParam.getRptGroupId())) {
            queryWrapper.eq(QcOutControlRec::getRptGroupId,pageParam.getRptGroupId());
        }
        if (StringUtils.isNotBlank(pageParam.getRptGroup())) {
            queryWrapper.eq(QcOutControlRec::getRptGroup,pageParam.getRptGroup());
        }
        if(ToolsUtils.isNotEmpty(pageParam.getOperateDateS())){
            queryWrapper.ge(QcOutControlRec::getOperateDate,pageParam.getOperateDateS());
        }
        if(ToolsUtils.isNotEmpty(pageParam.getOperateDateE())){
            queryWrapper.le(QcOutControlRec::getOperateDate,pageParam.getOperateDateE());
        }

        queryWrapper.orderByAsc(QcOutControlRec::getCreateTime);
        return Result.succ(1, "查询成功", qcOutControlRecMapper.selectList(queryWrapper));
    }

    @Override
    public Result getQcOutControlRecByRecId(String qcRecId) {
        MPJLambdaWrapper<QcOutControlRec> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(QcOutControlRec.class)
                .selectAs("ld", LabItemDict::getItemNa, QcOutControlRec::getItemDictName)
                .selectAs("ls", LabInstrSetup::getInstrName, QcOutControlRec::getInstrName)
                .selectAs("rpt", LabRptGroup::getId,QcOutControlRec::getRptGroupId)
                .selectAs("rpt", LabRptGroup::getRptGroupName,QcOutControlRec::getRptGroupName)
                .selectAs("em", SysUser::getRealname,QcOutControlRec::getReviewerName)
                .selectAs("res", QcMaterialItemResult::getResult,QcOutControlRec::getCorrectResult)
                .leftJoin(LabItemDict.class,"ld",LabItemDict::getId,QcOutControlRec::getItemDictId)
                .leftJoin(LabInstrSetup.class,"ls",LabInstrSetup::getId,QcOutControlRec::getInstrId)
                .leftJoin(LabRptGroup.class,"rpt",LabRptGroup::getRptGroup,LabItemDict::getRptGroup)
                .leftJoin(SysUser.class, "em", on -> on.eq(SysUser::getId, QcOutControlRec::getReviewerId).eq(SysUser::getDelFlag, 0))
                .leftJoin(QcMaterialItemResult.class,"res",p->p.eq(QcMaterialItemResult::getMaterialId,QcOutControlRec::getMaterialId)
                        .eq(QcMaterialItemResult::getMaterialItemId,QcOutControlRec::getMaterialItemId)
                        .eq(QcMaterialItemResult::getQcDate,QcOutControlRec::getQcDate)
                        .eq(QcMaterialItemResult::getIsBestInDay,1)
                        .eq(QcMaterialItemResult::getIsOutControl,0)
                        .eq(QcMaterialItemResult::getDelFlag,0)
                )
                .eq(QcOutControlRec::getId,qcRecId)
                .eq(QcOutControlRec::getDelFlag,0);
        QcOutControlRec qcOutControlRec = qcOutControlRecMapper.selectOne(queryWrapper);
        if(null != qcOutControlRec){
            LambdaQueryWrapper<QcOutControlRecDetail> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(QcOutControlRecDetail::getRecId,qcOutControlRec.getId())
                    .eq(QcOutControlRecDetail::getDelFlag,0);
            List<QcOutControlRecDetail> qcOutControlRecDetails = qcOutControlRecDetailMapper.selectList(queryWrapper1);
            qcOutControlRec.setDetails(qcOutControlRecDetails);
        }

        return Result.succ(1, "查询成功", qcOutControlRec);
    }
}
